import { lightAppJssdk, Decrypt } from './utils'
import store from '../store/index'
export const  newJisUrl = "http://zwfw.sd.gov.cn/JIS/sso/interface.do"; //接口地址

export const mainInit = () => {
  let userInfo = sessionStorage.getItem('userInfo');
  const userType = sessionStorage.getItem('userType');
  if (userInfo) {
    userInfo = JSON.parse(userInfo);
    store.commit('setState', { key: 'userInfo', value: userInfo });
  }
  if (userType) {
    store.commit('setState', { key: 'userType', value: userType });
  }
};

export const appInit = async (callback) => {
  await getUserInfo(callback)
};

export const getUserInfo = (callback) => {
  lightAppJssdk.user.getTicket({
    success(data) { // 成功回调
      if(data === '未登录') {
        onLoginApp(callback); // APP用户未登录，调用登录页面
      } else {
        const jsonData = JSON.parse(data);
        if (jsonData.retcode === '000000') {
          const { ticket } = setUserData(jsonData.data);
          getUserToken(ticket, callback);
        }
      }
    },
    fail() { // 错误返回
    }
  });
};

/**
 * 通过用户票据获取用户的令牌数据，票据使用一次后失效，token时效性较长
 */
export const getUserToken = async (ticket, callback) => {
  const params = {
    ticket
  };
  const data = {
    appmark: "sdzwapp",
    time: '20191215213400',
    sign: hex_md5("sdzwappaKd20dbGdFvmuwrt20191215213400"),
    servicename: "ticketValidate",
    params: JSON.stringify(params)
  };
  lightAppJssdk.request.request({
    url: newJisUrl,
    data: data,
    header: '',
    dataType: 'json', //返回数据格式，默认json
    async: true, //同步设置
    success(data) {
      if(data.retcode === '000000') {
        const userToken = JSON.parse(data.data).token;
        getUserInfoByToken(userToken, callback);
      } else {}
    }
  });
};

/**
 * 根据令牌获取个人完整信息
 */
export const getUserInfoByToken = async (userToken, callback) => {
  const servicename = (store.state.userType * 1 === 1 ? 'findOutsideUserByToken' : 'findCorUserByToken');
  let time = (new Date()).getTime();
  const params = {
    token: userToken
  };
  const data = {
    appmark: 'sdzwapp',
    time: '20191215213400',
    sign: hex_md5('sdzwappaKd20dbGdFvmuwrt20191215213400'),
    servicename,
    params: JSON.stringify(params)
  };
  lightAppJssdk.request.request({
    url: newJisUrl,
    data: data,
    header: '',
    dataType: 'json', //返回数据格式，默认json
    async: true, //同步设置
    success(data) {
      if(data.retcode === '000000') {
        let userInfo = Decrypt(data.data, "aKd20dbGdFvmuwrt");
        // console.log(userInfo)
        try {
          userInfo = JSON.parse(userInfo)
        } catch (e) {
          console.log(e)
        }
        store.commit('setState', { key: 'userInfo', value: userInfo });
        if (callback) {
          callback()
        }
      }
    },
    fail(data) {
    }
  });
};

/**
 * 使用jssdk调用登录页面
 */
export const onLoginApp = async (callback) => {
  lightAppJssdk.user.loginapp({
    success(data) {
      if(data === '未登录') {
        //取消登录或登录失败，关闭页面
        oncloseWindow();
      } else {
        const dataObj = JSON.parse(data);
        if(dataObj.retcode === '000000') { // 登录成功，返回用户的票据和用户类型
          const { ticket } = setUserData(dataObj.data);
          getUserToken(ticket, callback);
        } else {
          //关闭页面
          oncloseWindow();
        }
      }
    },
    fail(data) {
      //关闭页面
      oncloseWindow();
    }
  });
};

const setUserData = (data) => {
  const dataValueObj = JSON.parse(data);
  const ticket = dataValueObj.ticket; //解析出用户票据信息
  const userType = dataValueObj.usertype; //解析保存用户类型（个人法人）
  store.commit('setState', { key: 'userType', value: userType });
  return { ticket, userType }
};

/**
 * 关闭容器
 */
export const oncloseWindow = () => {
  lightAppJssdk.navigation.close({
    success: function(data) {},
    fail: function(data) {}
  });
};

export default {
  appInit,
  mainInit
}
